package com.weijing.pretty_app.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.weijing.pretty_app.R
import com.weijing.pretty_app.databinding.FragmentAlarmkBinding
import com.weijing.pretty_app.util.BluetoothSocketManager
import com.weijing.pretty_app.util.CoreUtil
import com.weijing.pretty_app.util.HexConverter
import com.weijing.pretty_app.util.KeyUtil
import com.weijing.pretty_app.util.SPUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

private const val TAG = "AlarmFragment"

/**
 * 警告页面
 */
class AlarmFragment : Fragment() {

    private lateinit var binding: FragmentAlarmkBinding
    private val default1Max = 38
    private val default1Min = 0
    private val default2Max = 2
    private val default2Min = 0
    private val default3Max = 30
    private val default3Min = 0

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentAlarmkBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        getSpData()
        initLClick()
        initRClick()
        initSaveAndRestClick()
    }

    private fun getSpData() {
        //左边设置
        binding.alarmEt1L.text =
            if (SPUtil.getString(KeyUtil.ALARM_L_1).isNullOrEmpty()) "0" else SPUtil.getString(
                KeyUtil.ALARM_L_1
            )
        binding.alarmEt2L.text =
            if (SPUtil.getString(KeyUtil.ALARM_L_2).isNullOrEmpty()) "0" else SPUtil.getString(
                KeyUtil.ALARM_L_2
            )
        binding.alarmEt3L.text =
            if (SPUtil.getString(KeyUtil.ALARM_L_3).isNullOrEmpty()) "0" else SPUtil.getString(
                KeyUtil.ALARM_L_3
            )
        //右边设置
        binding.alarmEt1R.text =
            if (SPUtil.getString(KeyUtil.ALARM_R_1).isNullOrEmpty()) "0" else SPUtil.getString(
                KeyUtil.ALARM_R_1
            )
        binding.alarmEt2R.text =
            if (SPUtil.getString(KeyUtil.ALARM_R_2).isNullOrEmpty()) "0" else SPUtil.getString(
                KeyUtil.ALARM_R_2
            )
        binding.alarmEt3R.text =
            if (SPUtil.getString(KeyUtil.ALARM_R_3).isNullOrEmpty()) "0" else SPUtil.getString(
                KeyUtil.ALARM_R_3
            )
    }

    private fun initRClick() {
        setupSmartIncrementButton(
            binding.alarmLl1RLeft, binding.alarmEt1R, false,
            1, default1Min, default1Max, binding.alarmCl1RLeft
        )
        setupSmartIncrementButton(
            binding.alarmLl1RRight, binding.alarmEt1R, true,
            1, default1Min, default1Max, binding.alarmCl1RRight
        )

        setupSmartIncrementButton(
            binding.alarmLl2RLeft, binding.alarmEt2R, false,
            1, default2Min, default2Max, binding.alarmCl2RLeft
        )
        setupSmartIncrementButton(
            binding.alarmLl2RRight, binding.alarmEt2R, true,
            1, default2Min, default2Max, binding.alarmCl2RRight
        )

        setupSmartIncrementButton(
            binding.alarmLl3RLeft, binding.alarmEt3R, false,
            1, default3Min, default3Max, binding.alarmCl3RLeft
        )
        setupSmartIncrementButton(
            binding.alarmLl3RRight, binding.alarmEt3R, true,
            1, default3Min, default3Max, binding.alarmCl3RRight
        )
    }

    private fun initLClick() {
        setupSmartIncrementButton(
            binding.alarmLl1LLeft, binding.alarmEt1L, false,
            1, default1Min, default1Max, binding.alarmCl1LLeft
        )
        setupSmartIncrementButton(
            binding.alarmLl1LRight, binding.alarmEt1L, true,
            1, default1Min, default1Max, binding.alarmCl1LRight
        )

        setupSmartIncrementButton(
            binding.alarmLl2LLeft, binding.alarmEt2L, false,
            1, default2Min, default2Max, binding.alarmCl2LLeft
        )
        setupSmartIncrementButton(
            binding.alarmLl2LRight, binding.alarmEt2L, true,
            1, default2Min, default2Max, binding.alarmCl2LRight
        )

        setupSmartIncrementButton(
            binding.alarmLl3LLeft, binding.alarmEt3L, false,
            1, default3Min, default3Max, binding.alarmCl3LLeft
        )
        setupSmartIncrementButton(
            binding.alarmLl3LRight, binding.alarmEt3L, true,
            1, default3Min, default3Max, binding.alarmCl3LRight
        )
    }

    private fun initSaveAndRestClick() {
        //左手柄重置
        binding.alarmIvLRest.setOnClickListener {
            binding.alarmEt1L.text = "38"
            binding.alarmEt2L.text = "2"
            binding.alarmEt3L.text = "30"
            //提示文案
            binding.alarmTvLOk.text = getString(R.string.reset_successfully)
            CoreUtil.showTvCustomToast(binding.alarmTvLOk)
            sendData("L", 38, 30, 2)
            initLClick()
        }

        //右手柄重置
        binding.alarmIvRRest.setOnClickListener {
            binding.alarmEt1R.text = "38"
            binding.alarmEt2R.text = "2"
            binding.alarmEt3R.text = "30"
            //提示文案
            binding.alarmTvROk.text = getString(R.string.reset_successfully)
            CoreUtil.showTvCustomToast(binding.alarmTvROk)
            sendData("R", 38, 30, 2)
            initRClick()
        }

        //左边保存
        binding.alarmIvLSave.setOnClickListener {
            SPUtil.put(KeyUtil.ALARM_L_1, binding.alarmEt1L.text.toString())
            SPUtil.put(KeyUtil.ALARM_L_2, binding.alarmEt2L.text.toString())
            SPUtil.put(KeyUtil.ALARM_L_3, binding.alarmEt3L.text.toString())

            CoreUtil.showTvCustomToast(binding.alarmTvLOk)
            sendData(
                "L", binding.alarmEt1L.text.toString().toInt(),
                binding.alarmEt3L.text.toString().toInt(), binding.alarmEt2L.text.toString().toInt()
            )
        }

        //右边保存
        binding.alarmIvRSave.setOnClickListener {
            SPUtil.put(KeyUtil.ALARM_R_1, binding.alarmEt1R.text.toString())
            SPUtil.put(KeyUtil.ALARM_R_2, binding.alarmEt2R.text.toString())
            SPUtil.put(KeyUtil.ALARM_R_3, binding.alarmEt3R.text.toString())

            CoreUtil.showTvCustomToast(binding.alarmTvROk)
            sendData(
                "R", binding.alarmEt1R.text.toString().toInt(),
                binding.alarmEt3R.text.toString().toInt(), binding.alarmEt2R.text.toString().toInt()
            )
        }
    }

    /**
     * @param isIncrement true代表加1 false代表减1
     */
    private fun setupSmartIncrementButton(
        button: View,
        targetTextView: TextView,
        isIncrement: Boolean,
        step: Int = 1,
        minValue: Int = Int.MIN_VALUE,
        maxValue: Int = Int.MAX_VALUE,
        backgroundTarget: View
    ) {
        var job: Job? = null

        fun updateValue() {  // 实时读取当前值
            val currentValue = targetTextView.text.toString().toIntOrNull() ?: 0
            val delta = if (isIncrement) step else -step
            var newValue = currentValue + delta

            // 限制最小最大值
            if (newValue < minValue) newValue = minValue
            if (newValue > maxValue) newValue = maxValue

            targetTextView.text = newValue.toString()
        }

        button.setOnClickListener {
            updateValue()
        }

        button.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    backgroundTarget.setBackgroundResource(R.drawable.button_click)
                    job = CoroutineScope(Dispatchers.Main).launch {
                        delay(500) // 长按启动延迟
                        while (isActive) {
                            updateValue()
                            delay(100)
                        }
                    }
                }

                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    job?.cancel()
                    backgroundTarget.setBackgroundResource(R.drawable.shape_circle_00c1cd)
                }
            }
            false
        }
    }

    /**
     * @param value1 水温
     * @param value2 手柄头温度
     * @param value3 水流
     */
    private fun sendData(fangXiang: String, value1: Int, value2: Int, value3: Int) {
        var mFangXiang = ""
        when (fangXiang) {
            "L" -> {
                mFangXiang = "01 "
            }

            "R" -> {
                mFangXiang = "02 "
            }
        }
        val data1 = HexConverter.intTo1ByteHex(value1)
        val value1Hex = data1.joinToString(" ") { "%02X".format(it) }

        val data2 = HexConverter.intTo1ByteHex(value2)
        val value2Hex = data2.joinToString(" ") { "%02X".format(it) }

        val data3 = HexConverter.intTo1ByteHex(value3)
        val value3Hex = data3.joinToString(" ") { "%02X".format(it) }

        val commandAll =
            KeyUtil.SETTING_ALARM_COMMAND + mFangXiang + value1Hex + " " + value2Hex + " " + value3Hex + KeyUtil.EE
        val data = HexConverter.hexStringToByteArray(commandAll)
        Log.i(TAG, "保存报警参数-- $commandAll")
        BluetoothSocketManager.send(data)
    }
}